package org.erp.spu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.erp.common.page.PageQueryModel;
import org.erp.spu.entity.SpuCategory;
import org.erp.spu.entity.SpuCategoryBrand;
import org.erp.spu.entity.vo.SpuBrandVo;
import org.erp.spu.entity.vo.SpuCategoryVo;
import org.erp.spu.mapper.SpuBrandMapper;
import org.erp.spu.entity.SpuBrand;
import org.erp.spu.mapper.SpuCategoryBrandMapper;
import org.erp.spu.mapper.SpuCategoryMapper;
import org.erp.spu.entity.bo.SpuBrandBo;
import org.erp.spu.entity.dto.SpuBrandDto;
import org.erp.spu.service.SpuBrandService;
import org.erp.spu.service.SpuCategoryBrandService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 品牌表(SpuBrand)表服务实现类
 *
 * @author dingding
 * @since 2025-11-05 11:22:17
 */

@Service("spuBrandService")
public class SpuBrandServiceImpl extends ServiceImpl<SpuBrandMapper, SpuBrand> implements SpuBrandService {

    @Resource
    private SpuBrandMapper spuBrandMapper;

    @Resource
    private SpuCategoryMapper spuCategoryMapper;

    @Resource
    private SpuCategoryBrandMapper spuCategoryBrandMapper;

    @Resource
    private SpuCategoryBrandService spuCategoryBrandService;




    /**
     * 查询所有数据
     * @param spuBrand
     * @return
     */
    @Override
    public List<SpuBrand> getList(SpuBrandBo spuBrand) {
        LambdaQueryWrapper<SpuBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SpuBrand::getBrandName,spuBrand.getBrandName());
        queryWrapper.eq(SpuBrand::getDelFlag,0);
        return this.baseMapper.selectList(queryWrapper);
    }



    /**
     * 新增数据
     * @param spuBrandDto
     * @return
     */
    @Override
    public boolean addSpuBrandDto(SpuBrandDto spuBrandDto) {
         Assert.isTrue(!this.checkBrandName(spuBrandDto), "品牌名称已存在");
         SpuBrand spuBrand = new SpuBrand();
         spuBrand.setBrandName(spuBrandDto.getBrandName());
         spuBrand.setStatus(spuBrandDto.getStatus());
        int result = spuBrandMapper.insert(spuBrand);
        if (!spuBrandDto.getCategoryIds().isEmpty() && result > 0) {
            spuBrandDto.getCategoryIds().forEach(categoryId -> {
                SpuCategory spuCategory = spuCategoryMapper.selectById(categoryId);
                if (spuCategory != null) {
                    SpuCategoryBrand spuCategoryBrand = new SpuCategoryBrand();
                    spuCategoryBrand.setBrandId(spuBrand.getId());
                    spuCategoryBrand.setBrandName(spuBrand.getBrandName());
                    spuCategoryBrand.setCategoryId(spuCategory.getId());
                    spuCategoryBrand.setCategoryName(spuCategory.getCategoryName());
                    spuCategoryBrandMapper.insert(spuCategoryBrand);
                }
            });
        }
        return result > 0;
    }
     /**
     * 修改数据
     * @param spuBrandDto
     * @return
     */
     
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSpuBrandDto(SpuBrandDto spuBrandDto) {
         // 检查品牌名称是否已存在
         Assert.isTrue(!this.checkBrandName(spuBrandDto), "品牌名称已存在");
         SpuBrand spuBrand = new SpuBrand();

         // 更新品牌基本信息
         BeanUtils.copyProperties(spuBrandDto, spuBrand);

         int result = spuBrandMapper.updateById(spuBrand);
         if (result > 0) {
             // 先删：删除该品牌下所有分类关联
             LambdaQueryWrapper<SpuCategoryBrand> deleteAllWrapper = new LambdaQueryWrapper<>();
             deleteAllWrapper.eq(SpuCategoryBrand::getBrandId, spuBrandDto.getId());
             spuCategoryBrandMapper.delete(deleteAllWrapper);
             // 后加：按传入分类ID重建关联
            if (spuBrandDto.getCategoryIds() != null && !spuBrandDto.getCategoryIds().isEmpty()) {
                List<SpuCategory> categories = spuCategoryMapper.selectBatchIds(spuBrandDto.getCategoryIds());
                if (categories != null && !categories.isEmpty()) {
                    List<SpuCategoryBrand> relations = categories.stream().map(spuCategory -> {
                        SpuCategoryBrand r = new SpuCategoryBrand();
                        r.setBrandId(spuBrandDto.getId());
                        r.setBrandName(spuBrand.getBrandName());
                        r.setCategoryId(spuCategory.getId());
                        r.setCategoryName(spuCategory.getCategoryName());
                        return r;
                    }).collect(Collectors.toList());
                    spuCategoryBrandService.saveBatch(relations);
                }
            }
         }
         return result > 0;
     }

    @Override
    public SpuBrandVo getDetails(Long id) {
        // 查询品牌基本信息
        SpuBrand spuBrand = this.getById(id);
        if (spuBrand == null) {
            return null;
        }

        // 将品牌实体转换为VO对象
        SpuBrandVo spuBrandVo = new SpuBrandVo();
        BeanUtils.copyProperties(spuBrand, spuBrandVo);

        // 查询并设置关联的分类列表
        LambdaQueryWrapper<SpuCategoryBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuCategoryBrand::getBrandId, id);
        queryWrapper.eq(SpuCategoryBrand::getDelFlag, 0);
        List<SpuCategoryBrand> categoryBrands = spuCategoryBrandMapper.selectList(queryWrapper);
        // 转换为分类VO列表
        List<SpuCategoryVo> categoryList = categoryBrands.stream()
                .map(categoryBrand -> {
                    SpuCategoryVo categoryVo = new SpuCategoryVo();
                    BeanUtils.copyProperties(categoryBrand, categoryVo);
                    return categoryVo;
                })
                .collect(Collectors.toList());
        spuBrandVo.setCategoryList(categoryList);
        return spuBrandVo;
    }


    /**
     * 分页查询所有数据
     * @param spuBrandDto
     * @return
     */
    @Override
    public PageQueryModel<SpuBrandVo> getListByPage(SpuBrandDto spuBrandDto) {
        LambdaQueryWrapper<SpuBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(spuBrandDto.getBrandName()), SpuBrand::getBrandName, spuBrandDto.getBrandName());
        queryWrapper.eq(SpuBrand::getDelFlag, 0);
        Page<SpuBrand> page = this.page(spuBrandDto.buildPage(), queryWrapper);

        List<SpuBrand> brands = page.getRecords();
        if (brands == null || brands.isEmpty()) {
            return PageQueryModel.of(page.getPages(), java.util.Collections.emptyList());
        }

        // 批量查询分类关联
        List<Long> brandIds = brands.stream().map(SpuBrand::getId).collect(Collectors.toList());
        LambdaQueryWrapper<SpuCategoryBrand> categoryBrandQueryWrapper = new LambdaQueryWrapper<>();
        categoryBrandQueryWrapper.in(SpuCategoryBrand::getBrandId, brandIds);
        categoryBrandQueryWrapper.eq(SpuCategoryBrand::getDelFlag, 0);
        List<SpuCategoryBrand> categoryBrandList = spuCategoryBrandMapper.selectList(categoryBrandQueryWrapper);

        java.util.Map<Long, List<SpuCategoryBrand>> brandIdToRelations = categoryBrandList.stream()
                .collect(Collectors.groupingBy(SpuCategoryBrand::getBrandId));

        List<SpuBrandVo> voList = brands.stream()
                .map(item -> {
                    SpuBrandVo spuBrandVo = new SpuBrandVo();
                    spuBrandVo.setId(item.getId());
                    spuBrandVo.setBrandName(item.getBrandName());
                    spuBrandVo.setStatus(item.getStatus());
                    spuBrandVo.setCreateTime(item.getCreateTime());

                    List<SpuCategoryBrand> relations = brandIdToRelations.getOrDefault(item.getId(), java.util.Collections.emptyList());
                    spuBrandVo.setCategoryList(relations.stream()
                            .map(categoryBrand -> {
                                SpuCategoryVo spuCategoryVo = new SpuCategoryVo();
                                spuCategoryVo.setId(categoryBrand.getCategoryId());
                                spuCategoryVo.setCategoryName(categoryBrand.getCategoryName());
                                return spuCategoryVo;
                            }).collect(Collectors.toList()));

                    return spuBrandVo;
                }).collect(Collectors.toList());
        return PageQueryModel.of(page.getPages(), voList);

    }

    /**
     * 检查品牌名称是否已存在
     * @param spuBrandDto
     * @return
     */
    private boolean checkBrandName(SpuBrandDto spuBrandDto) {
        LambdaQueryWrapper<SpuBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuBrand::getBrandName, spuBrandDto.getBrandName());
        queryWrapper.eq(SpuBrand::getDelFlag, 0);
        // 如果是修改操作，排除当前品牌自身
        if (spuBrandDto.getId() != null) {
            queryWrapper.ne(SpuBrand::getId, spuBrandDto.getId());
        }
        return spuBrandMapper.selectCount(queryWrapper) > 0;
    }
}

